#!/bin/bash
set -e

while getopts  ":s:p:l" opts
do
        case  $opts  in
        s)
                        sample_name=$OPTARG
                        
                ;;
		p)
                        out_prefix=$OPTARG;;
		l)
		bwa_aln=true
		;;
		\?)
			echo `basename $0` '[-s sample_name] [-p out_prefix] [-l] <single_end.fq>'
			exit 1
			;;
        esac
done
shift $(($OPTIND - 1))

if [ $# -lt 1 ]; then
        echo `basename $0` [-s sample_name] [-p out_prefix] [-l] single_end.fq
        exit 1
fi

#-----------------------------------------------
#-----------------------------------------------
. /mnt/ilustre/app/medical/tools/.var #---------
exec 1>>.log
exec 2>>.log
#-----------------------------------------------
#-----------------------------------------------




if [ -z $out_prefix ]; then
	out_prefix=1
fi



echo Sample name is: $sample_name
echo out prefix is: $out_prefix



# read_group=@RG\\tID:${sample_name}\\tPL:ILLUMINA\\tSM:$sample_name

if test -z $bwa_aln
then
echo;echo;echo start bwa mem se ...
bwa mem -M -L 100 -t 10 -R $read_group $ref_genome \
$1 \
> $out_prefix.sam \
2>> $log
else
echo;echo;echo start bwa aln ...
bwa aln -t 10 $ref_genome $1 > $out_prefix.sai
# bwa aln -t 10 $ref_genome $2 > $out_prefix.2.sai 2>>$log
bwa samse \
-n 10000 \
$ref_genome \
$out_prefix.sai \
$1 \
> $out_prefix.sam \
2>>$log
fi

# -r $read_group \ # it’s a bug?!






# $bwa mem -M -L 1000 -t 10 -R $read_group $ref_genome \
# $1 \
# $2 \
# > $out_prefix.sam \
# 2>> $log

echo
echo
echo 'samtools sam->bam sort index'

samtools view -@ 10 -F 4 -Sb $out_prefix.sam > $out_prefix.bam

if
java -jar $picard_path0/AddOrReplaceReadGroups.jar \
I=$out_prefix.bam \
O=$out_prefix.sort.bam \
SO=coordinate \
CREATE_INDEX=true \
SM=$sample_name \
ID=$sample_name \
LB=$sample_name \
PL=illumina \
PU=barcode \
2>>$log
then
echo 
echo picard AddOrReplaceReadGroups
else
samtools sort -@ 9 -m 2G -O bam -T $out_prefix $out_prefix.bam > $out_prefix.sort.bam 2>> $log
samtools index $out_prefix.sort.bam
fi
 


